﻿using Admin.NET.Application.Const;
using Admin.NET.Application.Entity;
using Admin.NET.Application.ServiceApi.Model;
using Furion.FriendlyException;
using MGee.Http;
using Microsoft.AspNetCore.Authorization;
using System;
using System.Collections.Generic;
 

namespace Admin.NET.Application;
/// <summary>
/// 用户服务
/// </summary>[AllowAnonymous]
[AllowAnonymous]
[ApiDescriptionSettings(ApplicationConst.GroupNameApi, Order = 100)]
public class car_appuserServiceaPI : IDynamicApiController, ITransient
{
    private readonly SqlSugarRepository<car_appuser> _rep;
    public car_appuserServiceaPI(SqlSugarRepository<car_appuser> rep)
    {
        _rep = rep;
    }

    string appid = "wx840b06c730bf7fc3";
    string secret = "756107f9e3ea10e679057feb3c24c836";
    /// <summary>
    /// 登录 ：只对code进行了兑换 拿到openid 返回数据
    /// </summary>
    /// <param name="logininfo">微信登录信息</param>
    /// <returns>返回用户信息</returns>
    [HttpPost]
    public object Login(LoginRequest logininfo)
    {
        //logininfo.Code = "043uqApN12UXF61L2GpN1rdNpN1uqAph";
        //去微信获取openid
        HttpHelper httpHelper = new HttpHelper();
        HttpItem httpItem = new HttpItem()
        {
            URL = "https://api.weixin.qq.com/sns/jscode2session?appid="+ appid + "&secret="+ secret + "&js_code=" + logininfo.Code + "&grant_type=authorization_code"
        };
        HttpResult httpResult = httpHelper.GetHtml(httpItem);
        UserInfo userInfo = HttpHelper.JsonToObject<UserInfo>(httpResult.Html);

        //   userInfo.OpenId = "oHdwE5kraj_aP5og1heROG2h395g";
        if (userInfo.OpenId == null)
        {
            throw new Exception("微信服务器错误");
        }

       car_appuser reAppUser =    _rep.GetFirst(u => u.miniOpenid == userInfo.OpenId);

     
        if (reAppUser == null)
        {
            //直接用openid 新建用户
             reAppUser = new car_appuser()
            {
                miniOpenid=userInfo.OpenId,
            };
            reAppUser.Id= _rep.InsertReturnEntity(reAppUser).Id;

        }
       

        return new
        {
          
            UserId = reAppUser.Id,
            //  IndexData=loginRespone
        };


    }


    /// <summary>
    /// 分页查询用户
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpPost]
    [ApiDescriptionSettings(Name = "Page")]
    public async Task<SqlSugarPagedList<car_appuserOutput>> Page(car_appuserInput input)
    {
        var query= _rep.AsQueryable()
                    .WhereIF(!string.IsNullOrWhiteSpace(input.miniOpenid), u => u.miniOpenid.Contains(input.miniOpenid.Trim()))
                    .WhereIF(input.phoneNo>0, u => u.phoneNo == input.phoneNo)

                    .Select<car_appuserOutput>()
;
        query = query.OrderBuilder(input);
        return await query.ToPagedListAsync(input.Page, input.PageSize);
    }

    /// <summary>
    /// 增加用户
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpPost]
    [ApiDescriptionSettings(Name = "Add")]
    public async Task Add(Addcar_appuserInput input)
    {
        var entity = input.Adapt<car_appuser>();
        await _rep.InsertAsync(entity);
    }

    /// <summary>
    /// 删除用户
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpPost]
    [ApiDescriptionSettings(Name = "Delete")]
    public async Task Delete(Deletecar_appuserInput input)
    {
        var entity = await _rep.GetFirstAsync(u => u.Id == input.Id) ?? throw Oops.Oh(ErrorCodeEnum.D1002);
        await _rep.FakeDeleteAsync(entity);   //假删除
    }

    /// <summary>
    /// 更新用户
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpPost]
    [ApiDescriptionSettings(Name = "Update")]
    public async Task Update(Updatecar_appuserInput input)
    {
        var entity = input.Adapt<car_appuser>();
        await _rep.AsUpdateable(entity).IgnoreColumns(ignoreAllNullColumns: true).ExecuteCommandAsync();
    }

    /// <summary>
    /// 获取用户
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpGet]
    [ApiDescriptionSettings(Name = "Detail")]
    public async Task<car_appuser> Get([FromQuery] QueryByIdcar_appuserInput input)
    {
        return await _rep.GetFirstAsync(u => u.Id == input.Id);
    }

    /// <summary>
    /// 获取用户列表
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpGet]
    [ApiDescriptionSettings(Name = "List")]
    public async Task<List<car_appuserOutput>> List([FromQuery] car_appuserInput input)
    {
        return await _rep.AsQueryable().Select<car_appuserOutput>().ToListAsync();
    }





}


public class LoginRequest
{
    public string Code { set; get; }
    public string EncryptedData { set; get; }
    public string Iv { set; get; }
}
